<?php

namespace app\common\model\merchant;
use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 积分商城轮播图
 */
class MerchantPointMallBannerModel extends BaseModel
{
    //
    protected $name = 'merchant_point_mall_banner';

    /**
     * 列表
     * @param $where
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list($where){
        return  $this->db()->where($where)->order('sort desc')
            ->field('id,pic,create_at,status,sort,type,type as type_name,pro_id,pro_id as pro_name')
            ->withAttr([
                'type_name' => function($v){
                    $array = [0 => '不跳',1 => '分类' , 2 => '商品'];
                    return $array[$v] ?? '无需跳转';
                },
                'pro_name' => function($v){
                    if ((int)$v > 0){
                        return $this->db('merchant_product_point')->where('id',$v)->value('title') ?? '';
                    }
                    return  '';
                }
            ])
            ->select();
    }

    /**
     * 详情
     * @param $where
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function info($where){
        return  $this->db()->where($where)->field('id,pic,create_at,status,sort,type,type as type_name,pro_id,pro_id as pro_name')
            ->withAttr([
                'type_name' => function($v){
                    $array = [0 => '不跳',1 => '分类' , 2 => '商品'];
                    return $array[$v] ?? '无需跳转';
                },
                'pro_name' => function($v){
                    if ((int)$v > 0){
                        return $this->db('merchant_product_point')->where('id',$v)->value('title') ?? '';
                    }
                    return  '';
                }
            ])
            ->find();
    }

    /**
     * 删除
     * @param $where
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function del($where){
        return  $this->db()->where($where)->delete();
    }

    /**
     * 保存
     * @param $where
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function save($data){
        $id = $data['id'];
        unset($data['id']);
        if (empty($id)){
            return  $this->db()->insert($data);
        }
        return  $this->db()->where('id',$id)->update($data);
    }
}
